import java.util.Arrays;

public class Sort {
    /*
    public static void mergeSort(int[]array) {
        mergeInternal(array, 0, array.length - 1);
    }
    public static void mergeInternal(int[]array,int left,int right){
        if(left>=right){
            return;
        }
        int mid=left+((right-left)>>>1);
        mergeInternal(array,left,mid);
        mergeInternal(array,mid+1,right);
        merge(array,left,mid,right);
    }*/
    public static void merge(int[]array,int start,int mid,int end){
        int s1=start;
        int e1=mid;
        int s2=mid+1;
        int e2=end;
        int []tmp=new int[end-start+1];
        int k=0;
        while(s1<=e1&&s2<=e2){
            if(array[s1]<array[s2]){
                tmp[k++]=array[s1++];
            }else{
                tmp[k++]=array[s2++];
            }
        }
        while(s1<=e1){
            tmp[k++]=array[s1++];
        }
        while(s2<=e2){
            tmp[k++]=array[s2++];
        }
        for (int i = 0; i < k; i++) {
            array[i+start]=tmp[i];
        }

    }
    public static void mergeSort(int[]array){
        int nums=1;
        while(nums<array.length){
            for (int i = 0; i < array.length; i+=2*nums) {
                int left=i;
                int mid=left+nums-1;
                if(mid>=array.length){
                    mid=array.length-1;
                }
                int right=mid+nums;
                if(right>=array.length){
                    right=array.length-1;
                }
                merge(array,left,mid,right);
            }
            nums*=2;
        }
    }


    public static void main(String[] args) {
        int[]array={33,22,11,45,32,22,1};
        mergeSort(array);
        System.out.println(Arrays.toString(array));
    }
}
